package com.sunmi.usercenter.ui.activity.fragment;

import org.apache.http.Header;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.sunmi.usercenter.Constant;
import com.sunmi.usercenter.R;
import com.sunmi.usercenter.bean.FmInfo;
import com.sunmi.usercenter.bean.Result;
import com.sunmi.usercenter.bean.Shop;
import com.sunmi.usercenter.bean.UserLoginInfo;
import com.sunmi.usercenter.bean.rpc.ReqLogin;
import com.sunmi.usercenter.ui.activity.HomeActivity;
import com.sunmi.usercenter.ui.component.LoadingDialog;
import com.sunmi.usercenter.ui.component.NetErrorDialog;
import com.sunmi.usercenter.ui.component.NetErrorDialog.TwoToDoOnClickListener;
import com.sunmi.usercenter.utils.MD5Utils;
import com.sunmi.usercenter.utils.NetWorkCenterUtils;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.Selection;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.lang.reflect.Type;

/**
 * 项目名称：Sunmi-User-Center
 * 类描述：登录商米账号的界面
 * 创建人：Abtswiath丶lxy
 * 创建时间：2016/6/7 11:33
 * 修改人：longx
 * 修改时间：2016/6/7 11:33
 * 修改备注：
 */
public class LoginFragment extends SuperFragment implements OnClickListener, TwoToDoOnClickListener {

    private View mView;
    private EditText mEditUsername;
    private EditText mEditPassword;
    private LinearLayout mLinShowPsd;
    private ImageView mImgEye;
    private TextView mTxtError, mBtnLogin, mTxtForgetPsd, mTxtNewAccount;
    private RelativeLayout mRelBack, mRelClearUserName, mRelClearPassword;
    private boolean isHidden = true;//是否隐藏输入框文本
    private boolean editUsernameIsNull = true, editPasswordIsNull = true;
    private NetErrorDialog netErrorDialog;
    private String usr = "";

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Object obj = getInfo();
        if(obj!=null){
            usr = (String)obj;
        }
        Shop shop = mCaCheModel.getShop();
        if (shop != null) {
            openFM(new FmInfo(UserAllInfoFragment.class, null));
        } else {
            initView();
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden) {
            if (!Constant.ME_IS_LAUNCHER) {
                Constant.CLASS_FRAGMENT = Constant.DoubleClickExit;
            }
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        return mView = inflater.inflate(R.layout.fragment_login, container, false);
    }

    /**
     * 初始化
     */
    private void initView() {
        if (!Constant.ME_IS_LAUNCHER) {
            Constant.CLASS_FRAGMENT = Constant.DoubleClickExit;
        }
        mActivity.SetStatusColorf5f5f5();
        TextView mTxtTitle = (TextView) mView.findViewById(R.id.title);
        layoutTitle(mTxtTitle);
        mEditUsername = (EditText) mView.findViewById(R.id.edit_login_username);
        mEditPassword = (EditText) mView.findViewById(R.id.txt_password);
        mRelBack = (RelativeLayout) mView.findViewById(R.id.back);
        mLinShowPsd = (LinearLayout) mView.findViewById(R.id.ln_show_psd);
        mImgEye = (ImageView) mView.findViewById(R.id.img_eye);
        mTxtError = (TextView) mView.findViewById(R.id.txt_error);
        mBtnLogin = (TextView) mView.findViewById(R.id.btn_login);
        mTxtForgetPsd = (TextView) mView.findViewById(R.id.txt_forget_pad);
        mTxtNewAccount = (TextView) mView.findViewById(R.id.txt_new_account);
        mRelClearUserName = (RelativeLayout) mView.findViewById(R.id.rel_clear_username);
        mRelClearPassword = (RelativeLayout) mView.findViewById(R.id.rel_clear_password);
        mRelClearPassword.setOnClickListener(this);
        mRelClearUserName.setOnClickListener(this);
        mRelBack.setOnClickListener(this);
        mLinShowPsd.setOnClickListener(this);
        mBtnLogin.setOnClickListener(this);
        mTxtForgetPsd.setOnClickListener(this);
        mTxtNewAccount.setOnClickListener(this);
        if (!Constant.ME_IS_LAUNCHER) {
            mRelBack.setVisibility(View.GONE);
        }
        mBtnLogin.setBackgroundResource(R.drawable.btn_bg_no_click2);
        mBtnLogin.setEnabled(false);
        editChangeListenter();
    }

    @Override
    public void onResume() {
        super.onResume();
        Object obj = getInfo();
        usr = "";
        if(obj!=null){
            usr = (String)obj;
        }
        if(!TextUtils.isEmpty(usr)) {
            mEditUsername.setText(usr);
        }else{
            mEditUsername.setText(mCaCheModel.getUserName());
        }
        mEditPassword.setText("");
    }

    /**
     * 是否显示文本框的内容
     */
    private void showPsdOrHidePsd() {
        if (isHidden) {
            mEditPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            mImgEye.setBackgroundResource(R.drawable.eye_yes);
        } else {
            mEditPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            mImgEye.setBackgroundResource(R.drawable.eye_no);
        }
        isHidden = !isHidden;
        mEditPassword.postInvalidate();
        //切换后将EditText光标置于末尾
        CharSequence charSequence = mEditPassword.getText();
        if (charSequence instanceof Spannable) {
            Spannable spanText = (Spannable) charSequence;
            Selection.setSelection(spanText, charSequence.length());
        }
    }

    private void login() {
        if (!NetWorkCenterUtils.isNetworkConnected(getActivity())) {
            netErrorDialog = NetErrorDialog.createDialog(getActivity(), this);
            netErrorDialog.show();
        }
        final LoadingDialog mLoadingDialog = LoadingDialog.createDialog(getActivity(), getString(R.string.logining));
        mLoadingDialog.show();
        final String username = mEditUsername.getText().toString().trim();
        final String password = mEditPassword.getText().toString();
        ReqLogin reqLogin = new ReqLogin();
        reqLogin.setPassword(MD5Utils.md5Password(username, password));
        reqLogin.setUserName(username);
        mHttpController.login(reqLogin, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int arg0, Header[] arg1, byte[] resultByte) {
                loginSuccess(resultByte,username);
                mLoadingDialog.dismiss();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
                mLoadingDialog.dismiss();
            }
        });
    }

    void loginSuccess(byte[] resultByte,String username){
        String json = new String(resultByte);
        Gson gson = new Gson();
        Type type = new TypeToken<Result<Shop>>() {
        }.getType();
        Result<Shop> result = null;
        try {
            result = gson.fromJson(json, type);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (result != null && result.getCode() == 1) {
            showToast(getString(R.string.login_success));
            if (result.data != null) {
//                showToast("uid:"+result.data.getuId());
                mCaCheModel.saveShop(result.data);
            }
            if (Constant.ME_IS_LAUNCHER) {
                exitMe();
                getActivity().finish();
            } else {
                openFM(new FmInfo(UserAllInfoFragment.class, null));
            }
            mCaCheModel.saveLoginUserName(username);
        } else if (result != null && (result.getCode() == 303 || result.getCode() == 304)) {
            showToast(getString(R.string.the_account_is_disabled));
        } else {
            mTxtError.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                onBack();
                break;
            case R.id.ln_show_psd:
                showPsdOrHidePsd();
                break;
            case R.id.btn_login:
                login();
                break;
            case R.id.txt_forget_pad:
                openFM(new FmInfo(RetrievePsdFragment.class, null));
                break;
            case R.id.txt_new_account:
                Constant.mInputToCode.setFramgmentCode(1);
                mCaCheModel.clearRegister();
                openFM(new FmInfo(RegisterFragment.class, null));
                break;
            case R.id.rel_clear_username:
                mEditUsername.setText("");
                break;
            case R.id.rel_clear_password:
                mEditPassword.setText("");
                break;
            default:
                break;
        }
    }

    private void editChangeListenter() {
        mEditPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    mRelClearPassword.setVisibility(View.VISIBLE);
                } else {
                    mRelClearPassword.setVisibility(View.GONE);
                }
                editPasswordIsNull = s.length() < 6;
                changeLoginBtn();
            }
        });
        mEditUsername.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    mRelClearUserName.setVisibility(View.VISIBLE);
                } else {
                    mRelClearUserName.setVisibility(View.GONE);
                }
                editUsernameIsNull = s.length() == 0;
                changeLoginBtn();
            }
        });

}

    private void changeLoginBtn() {
        if (!editPasswordIsNull && !editUsernameIsNull) {
            mBtnLogin.setBackgroundResource(R.drawable.btn_bg);
            mBtnLogin.setEnabled(true);
        } else {
            mBtnLogin.setBackgroundResource(R.drawable.btn_bg_no_click2);
            mBtnLogin.setEnabled(false);
        }
    }

    @Override
    public void changNet() {
        intentWifi();
        netErrorDialog.dismiss();
    }

    @Override
    public void ok() {
        netErrorDialog.dismiss();
    }

}
